# -*- coding: utf-8 -*-
import PIL
from PIL import Image
import sys
import os
import shutil

# image = Image.open("0.png")
# image.show()

#将获取的图片处理成正方形
def fill_image(image):
    width,height = image.size
  
    #选取长和宽中较大值作为新图片的
    new_image_length = width if  width > height else height
    #生成新的图片，填充白色背景
    new_image = Image.new(image.mode,(new_image_length,new_image_length),color='white')
    #将获得的图片填充到新的图中，居中
    if width>height:
        new_image.paste(image,(0,int((new_image_length-height)/2)))
    else:
        new_image.paste(image,(int((new_image_length-width)/2),0))
    return new_image

#将获得的正方形图片分割9张小图
def cut_image(image):
    width,height=image.size
    item_width = int(width / 3)
    box_list = []
    for i in range(0,3):
        for j in range(0,3):
            box = (j*item_width,i*item_width,(j+1)*item_width,(i+1)*item_width)
            box_list.append(box)
    image_list = [image.crop(box) for box in box_list]
    return image_list

#保存处理好的图片
def save_images(image_list,savaPathStr):
    print(savaPathStr)
    index = 1
    for image in image_list:
        imagepath = ''
        if not savaPathStr:
            imagepath = str(index)+'.png'
        else:
            imagepath = savaPathStr +'\\'+ str(index)+'.png'
        image.save(imagepath,'PNG')
        index += 1
        
        
def mkdir(path):
    folder = os.path.exists(path)
    if folder is True:
        shutil.rmtree(path)
        
    os.makedirs(path)

if __name__ == '__main__':
    file_path = '0.png'
    
    imagesource = os.getcwd() +'\\'+'huarongdao'+'\\'
    print(imagesource)
    mkdir(imagesource + "cutimages")
    image = Image.open(imagesource + file_path)
    width,height = image.size
    image_list = []
    if width==height:
        image_list = cut_image(image)
    else:
        image_new = fill_image(image)
        image_list= cut_image(image_new)
    save_images(image_list,imagesource + "cutimages")
    
    
    